package com.niyue.sandbox.uclock.core;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;

public class SecondThread extends Thread {
	private static Logger logger = Logger.getLogger(SecondThread.class);
	private int delay;
	private SecondTickerEventFactory factory;
	@Override
	public void run() {
		long startTime = System.currentTimeMillis();
		while(true){
			Event tickerEvent = new SecondTickerEvent(new DateTime());
			factory.addEvent(tickerEvent);
			startTime += delay;
            try {
				Thread.sleep(Math.max(0L, startTime - System.currentTimeMillis()));
			} catch (InterruptedException e) {
				logger.error("Some problem occurs at thread sleeping. "+e.getMessage());
			}
		}
	}

	@Override
	public synchronized void start() {
		super.start();
	}

	public SecondThread(SecondTickerEventFactory factory) {
		super();
		this.factory = factory;
		//1 second delay
		delay=1000;
	}	
}
